package cn.gengar.mybatis.test;


import cn.gengar.mybatis.binding.MapperProxyFactory;
import cn.gengar.mybatis.binding.MapperRegistry;
import cn.gengar.mybatis.datasource.pooled.PooledDataSource;
import cn.gengar.mybatis.io.Resources;
import cn.gengar.mybatis.session.SqlSession;
import cn.gengar.mybatis.session.SqlSessionFactory;
import cn.gengar.mybatis.session.SqlSessionFactoryBuilder;
import cn.gengar.mybatis.session.defaults.DefaultSqlSessionFactory;
import cn.gengar.mybatis.test.dao.IUserDao;
import cn.gengar.mybatis.test.po.User;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

@Slf4j
public class ApiTest {

    @Test
    public void test_MapperProxyFactory() throws IOException {
        // 1. 从SqlSessionFactory 中获取 sqlSession
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config-datasource.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSqlSession();

        // 2. 获取代理对象
        IUserDao userDao = sqlSession.getMapper(IUserDao.class);

        // 3. 测试，打印sql语句
        for (int i = 0; i < 50; i++) {
            User user = userDao.queryUserInfoById(1L);
            log.info("测试结果：{}", JSON.toJSONString(user));
        }
    }

    @Test
    public void test_pooled() throws SQLException, InterruptedException {
        PooledDataSource pooledDataSource = new PooledDataSource();
        pooledDataSource.setDriver("com.mysql.jdbc.Driver");
        pooledDataSource.setUrl("jdbc:mysql://115.120.226.239:13306/mybatis_test?useUnicode=true");
        pooledDataSource.setUsername("root");
        pooledDataSource.setPassword("123456");
        // 持续获得链接
        while (true) {
            Connection connection = pooledDataSource.getConnection();
            log.info("connection:{}", connection);
            Thread.sleep(10000);
            connection.close();
        }
    }

}